#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <vector>

using namespace std;
using namespace cv;

void process()
{
    // Mat img = cv::imread("/Users/lianwencong/ACC项目/image/Pic_2021_09_15_175022_3.bmp", 2);
    // Mat img = cv::imread("/Users/lianwencong/ACC项目/image/Pic_2021_09_15_174615_1_1.jpg", 2);
    Mat img = cv::imread("img/cut1.tif", 2);
    // cv::imshow("img", img);
    // cv::waitKey();
    // 首先对图像进行滤波和二值化处理
    Mat thresImg, blurImg;
    GaussianBlur(img, blurImg, Size(5, 5), 1, 1);
    adaptiveThreshold(blurImg, thresImg, 255, 0, CV_THRESH_BINARY, 33, 1);
    

    //找出所有轮廓
    //vector<vector<Point>> contours;
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    findContours(thresImg, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point());
    int i,j;
    double area;
    vector<Point> points;
    // 通过判断曲线的弯曲程度来判断是否有气泡，弯曲大的地方有
    // 这里的方法稳定性还不够高，但能检测到一部分
    for(i=0;i<contours.size();i++)
    {
        area = contourArea(contours[i]);
        if(area < 20)
        {
            continue;
        }
        for(j=3;j<contours[i].size();j++)
        {
            if(contours[i][j].x-contours[i][j-3].x > 5)
            {
                points.push_back(contours[i][j]);
            }
        }
    }
    for(i=0;i<points.size();i++)
    {
        rectangle(img,Rect(points[i],Size(20,20)),Scalar(200),3);
    }
    //imshow("img",img);
    //threshold(img, thresImg, 130, 255, CV_THRESH_BINARY);
    // imshow("img", thresImg);
    // imwrite("img/res5.tif", thresImg);
    imwrite("img/result2.tif",img);
     //waitKey();
}

void cutImg()
{
    string inputPath = "/Users/lianwencong/ACC项目/image/Pic_2021_09_15_175022_3.bmp";
    // string outputPath = "";
    Mat img = imread(inputPath, 2);
    Mat roi = img(Rect(Point(3000, 1500), Size(3500, 2500)));
    imwrite("img/cut1.tif", roi);
}

int main()
{
    //cutImg();
    process();
    return 0;
}